package cn.lanqiao.book.controller;



import cn.lanqiao.book.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/*
*  用于处理登录请求（ajax请求）
*  请求中应包含两个数据
* （String）username
* （String）password
* 如果登录验证成功 响应中返回 字符串 "Hello username!"
* 如果登陆失败 响应中返回 字符串 "用户名或密码错误"
* */
@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        resp.setCharacterEncoding("UTF-8");
        if(!UserServiceImpl.getInstance().checkPassword(username,password)){
            //如果登录失败返回一个错误信息
            resp.getWriter().write("error");

        }else {
            //如果密码验证成功，将用户信息保存到session中，以便于后续其他页面使用
            HttpSession session=req.getSession();
            session.setAttribute("username",username);
            //返回hello信息
            resp.getWriter().write("Hello "+username+"!");
        }

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
